<?php


namespace app\admin\controller;



use Qiniu\Storage\UploadManager;
use think\App;
use think\Request;
use Qiniu\Auth;

class UploadController extends CommonController
{

    private $GetUploadConf;

    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->GetUploadConf = new ConfigController();
    }

    //上传至七牛云
    public function upload(Request $request)
    {
        $file=$request->file();
        $size=ceil($file['file']->getSize()/1024); //获取kb
        $size=ceil($size/2048);
        if ($size>2){
            return returnFail('上传不能超过2MB');
        }
        $rule = ['jpg', 'png', 'gif','jpeg'];

        $upload_type=$this->GetUploadConf->GetUploadConf();
        switch ($upload_type){
            case 1:
                //本地
                $ext = pathinfo($file['file']->getInfo('name'), PATHINFO_EXTENSION);
                if (!in_array($ext,$rule)){
                    return returnFail('上传格式错误');
                }
                $url_path = 'uploads/local';
                $info = $file['file']->move( $url_path);
                if ($info){
                    $url = config('LOCAL_domain').'/'.$url_path.'/'.$info->getSaveName();
                    return returnSuccess(['url'=>$url],'success');
                }else{
                    return returnFail('本地上传失败');
                }
            case 2:
                //七牛云
                $filePath = $file['file']->getRealPath();
                $ext = pathinfo($file['file']->getInfo('name'), PATHINFO_EXTENSION);
                if (!in_array($ext,$rule)){
                    return returnFail('上传格式错误');
                }
                $key =substr(md5($file['file']->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
                $accessKey = config('QINIU_ACCESSKEY');
                $secretKey = config('QINIU_SECRETKEY');
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 要上传的空间
                $bucket = config('QINIU_BUCKET');
                $domain = config('QINIU_domain');
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return returnFail('七牛云上传错误');
                } else {
                    //返回图片的完整URL
                    return returnSuccess(['url'=>$domain.'/'.$ret['key']],'success');
                }
        }


    }

}